package com.dizang.cloud.controller;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.dizang.cloud.collapser.impl.UserBatchCollapser;
import com.dizang.cloud.collapser.impl.UserBatchServiceImpl;
import com.dizang.cloud.collapser.impl.UserBatchWithFutureServiceImpl;
import com.dizang.cloud.entity.User;

/**
 * 合并请求样例
 * @author kelvin.cai
 *
 */
@RestController
public class UserController {

    @Autowired
    private UserBatchServiceImpl userBatchServiceImpl;
    @Autowired
    private UserBatchWithFutureServiceImpl userBatchWithFutureServiceImpl;
    
    /**
     * 正常请求
     * @param id
     * @return
     */
    @RequestMapping(method = RequestMethod.GET,value = "/user/{id}")
    public User user(@PathVariable Long id) {
        User book = new User( 55L, "姚雪垠2");
        return book;
    }
    
    /**
     * hystrix注解形式合并请求
     * @param id
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     */
    @RequestMapping(method = RequestMethod.GET,value = "/userbyMerge/{id}")
    public User userbyMerge(@PathVariable Long id) throws InterruptedException, ExecutionException {
        Future<User> test10 = this.userBatchServiceImpl.getUserById(id);
        User user = test10.get();
        return user;
    }
    
    /**
     * hystrix编码形式合并请求
     * @param id
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     */
    @RequestMapping(method = RequestMethod.GET,value = "/userbyCommandMerge/{id}")
    public User userbyCommandMerge(@PathVariable Long id) throws InterruptedException, ExecutionException {
        UserBatchCollapser userBatchCollapser = new UserBatchCollapser(id);
        Future<User> queue = userBatchCollapser.queue();
        User user = queue.get();
        return user;
    }

    /**
     * 利用Future与线程池实现合并请求
     * @param id
     * @return
     * @throws InterruptedException
     * @throws ExecutionException
     */
    @RequestMapping(method = RequestMethod.GET,value = "/userbyMergeWithFuture/{id}")
    public User userbyMergeWithFuture(@PathVariable Long id) throws InterruptedException, ExecutionException {
        User user = this.userBatchWithFutureServiceImpl.getUserById(id);
        return user;
    }
    
    

}
